<template>
  <a-input-search
    placeholder="搜素成员或部门"
    v-model:value="searchValue"
    :allowClear="true"
    style="margin-bottom: 8px"
  >
  </a-input-search>
  <a-tree
    :checked-keys="checkedKeysLocal"
    v-if="treeList.length>0"
    :tree-data="treeList"
    checkable
    show-icon
    @check="onCheck"
    :fieldNames=" {children:'children', title:'name', key:'id' } "
    :expandedKeys="expandedKeys"
    :autoExpandParent="autoExpandParent"
    @expand="onExpand"
    :checkedKeys="checkedKeys"
  >
    <template #icon="{ type}">
      <template v-if="type == 0">
        <team-outlined />
      </template>
      <template v-else>
        <user-outlined/>
      </template>
    </template>
    <template #title="{ name }">
        <span v-if="name.indexOf(searchValue) > -1">
          {{ name.substr(0, name.indexOf(searchValue)) }}
          <span style="color: #f50">{{ searchValue }}</span>
          {{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
        </span>
      <span v-else>{{ name }}</span>
    </template>
  </a-tree>
</template>

<script lang="ts" setup>
import {onMounted, ref, toRefs, watch} from 'vue';
import { FolderOutlined, UserOutlined, TeamOutlined} from '@ant-design/icons-vue';
import {getDepartUserTree} from '@/api/base/tag/tag';
import {APP_USER} from '@/enums/cacheEnum';
import {Storage} from '@/utils/Storage';
const tenantid = ref(Storage.Get(APP_USER).tenantid);

defineOptions({
  name: 'treeList',
});
const props = defineProps({
  // 默认选中的节点
  checkedKeys: {
    type: Array,
    default: () => []
  }
})
// 定义所要传给父组件的值
const userIds = ref([])
// 传值给父组件
const emit = defineEmits(["getValue","getkvList"])

// 点击复选框触发 传值给父组件
const onCheck = (checkedKeys, e) => {
  const list = e.checkedNodes
    .filter(node => node.type === 1)
    .map(node => {
      return { key: node.id, value: node.name };
    });

  userIds.value = list.map(item => item.key);
  emit("getValue", userIds.value);
  emit("getkvList", list);
};

// 部门人员数列表
const treeList = ref([])
// 查询部门人员树
const getTreeList = async () => {
  const res = await getDepartUserTree({tenantId: tenantid.value})
  if (res.code == 0) {
    treeList.value = res.data
    generateList(treeList.value);
  }
}

// 展开的key
const expandedKeys = ref([]);
//搜索关键字
const searchValue = ref('');
//是否展开树
const autoExpandParent = ref(true);

// 展开收起触发
const onExpand = (keys) => {
  console.log('keys',keys)
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};

//处理数据，拿到 提取 key title  格式为 ：{key：key,title: node.title } Antd组件方法

const dataList = [];
const generateList = (data) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const key = node.id;
    dataList.push({
      key,
      title: node.name,
    });
    if (node.children) {
      generateList(node.children);
    }
  }
};
generateList(treeList.value);

//andt 组件方法 获取父级节点key
const getParentKey = (key, tree) => {
  // debugger
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];

    if (node.children) {
      if (node.children.some((item) => item.id === key)) {
        parentKey = node.id;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};

//搜索事件
watch(searchValue, value => {
  // debugger
  if (!value) return autoExpandParent.value = false;
  const expanded = dataList
    .map((item) => {
      if (item.title.indexOf(value) > -1) {
        return getParentKey(item.key, treeList.value);
      }
      return null;
    })
    .filter((item, i, self) => item && self.indexOf(item) === i);
  console.log('expand', expanded);
  expandedKeys.value = expanded;
  searchValue.value = value;
  autoExpandParent.value = true;
});

onMounted(() => {
  getTreeList();
})
</script>
